from datetime import datetime
from app import db
from sqlalchemy import Index

class UserRelation(db.Model):
    """用户关系模型（好友/黑名单）"""
    __tablename__ = 'user_relations'
    
    id = db.Column(db.Integer, primary_key=True)
    owner_id = db.Column(db.Integer, db.ForeignKey('users.id'), nullable=False, comment='关系发起者ID')
    target_id = db.Column(db.Integer, db.ForeignKey('users.id'), nullable=False, comment='被标记用户ID')
    relation_type = db.Column(db.Enum('friend', 'blacklist', name='relation_type'), nullable=False, comment='关系类型：friend=好友，blacklist=黑名单')
    created_at = db.Column(db.DateTime, default=datetime.now, comment='创建时间')
    updated_at = db.Column(db.DateTime, default=datetime.now, onupdate=datetime.now, comment='更新时间')
    
    # 关联关系
    owner = db.relationship('User', foreign_keys=[owner_id], backref='initiated_relations')
    target = db.relationship('User', foreign_keys=[target_id], backref='received_relations')
    
    # 复合唯一索引（一个用户对另一个用户只能有一种关系）
    __table_args__ = (
        Index('idx_owner_target', 'owner_id', 'target_id', unique=True),
        Index('idx_owner_type', 'owner_id', 'relation_type'),
        # 防止自己对自己建立关系
        db.CheckConstraint('owner_id != target_id', name='check_not_self_relation')
    )
    
    def __repr__(self):
        return f'<UserRelation owner_id={self.owner_id}, target_id={self.target_id}, type={self.relation_type}>'
    
    def to_dict(self, include_users=False):
        """转换为字典"""
        data = {
            'id': self.id,
            'owner_id': self.owner_id,
            'target_id': self.target_id,
            'relation_type': self.relation_type,
            'created_at': self.created_at.strftime('%Y-%m-%d %H:%M:%S') if self.created_at else None,
            'updated_at': self.updated_at.strftime('%Y-%m-%d %H:%M:%S') if self.updated_at else None
        }
        
        if include_users:
            if self.owner:
                data['owner'] = self.owner.to_dict()
            if self.target:
                data['target'] = self.target.to_dict()
                
        return data
    
    @classmethod
    def is_blacklisted(cls, owner_id, target_id):
        """检查target_id是否被owner_id拉黑"""
        return cls.query.filter_by(
            owner_id=owner_id,
            target_id=target_id,
            relation_type='blacklist'
        ).first() is not None
    
    @classmethod
    def is_friend(cls, owner_id, target_id):
        """检查target_id是否被owner_id标记为好友"""
        return cls.query.filter_by(
            owner_id=owner_id,
            target_id=target_id,
            relation_type='friend'
        ).first() is not None
    
    @classmethod
    def get_relation(cls, owner_id, target_id):
        """获取两个用户之间的关系"""
        return cls.query.filter_by(
            owner_id=owner_id,
            target_id=target_id
        ).first()
    
    @classmethod
    def set_relation(cls, owner_id, target_id, relation_type):
        """设置或更新用户关系"""
        if owner_id == target_id:
            raise ValueError("不能对自己建立关系")
            
        if relation_type not in ['friend', 'blacklist']:
            raise ValueError("关系类型必须是friend或blacklist")
        
        # 查找现有关系
        existing = cls.get_relation(owner_id, target_id)
        
        if existing:
            # 更新现有关系
            existing.relation_type = relation_type
            existing.updated_at = datetime.now()
            return existing
        else:
            # 创建新关系
            new_relation = cls(
                owner_id=owner_id,
                target_id=target_id,
                relation_type=relation_type
            )
            db.session.add(new_relation)
            return new_relation
    
    @classmethod
    def delete_user_relation(cls, owner_id, relation_type, target_id):
        """删除用户关系"""
        relation = cls.query.filter_by(
            owner_id=owner_id,
            target_id=target_id,
            relation_type=relation_type
        ).first()
        
        if relation:
            db.session.delete(relation)
            return True
        return False 